package com.cgs.springboottes2secrity.secfilter;

import cn.hutool.jwt.JWT;
import com.cgs.springboottes2secrity.entity.Admin;
import com.cgs.springboottes2secrity.vo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author cgs
 * @version woNiu 98
 * @date 2023/5/11 16:01
 */
public class ApiAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    public ApiAuthenticationFilter() {
        super(new AntPathRequestMatcher("/api/admin/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String ,String > map = objectMapper.readValue(request.getInputStream(), Map.class);
        String account = map.get("account");
        String password = map.get("pwd");

        ApiAuthenticationToken apiAuthenticationToken=new ApiAuthenticationToken(account,password,null);

        return this.getAuthenticationManager().authenticate(apiAuthenticationToken);
    }
}
